package net.oschina.app.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewSearchAdapter;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.SearchList;
import net.oschina.app.bean.SearchList.Result;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.TextView;

public class BaseSearchListFragment extends SearchPullToRefreshListFragment{
	private ListViewSearchAdapter lvSearchAdapter;
	private List<Result> lvSearchData = new ArrayList<Result>();
	private Handler mSearchHandler;
	private int lvSumData;
	private String curSearchCatalog = SearchList.CATALOG_SOFTWARE;
	private int curLvDataState;
	private String curSearchContent;

	public BaseSearchListFragment(String curSearchCatalog,
			OnBaseListFragmentResumeListener baseListFragmentResumeListener) {
		super(baseListFragmentResumeListener);
		this.curSearchCatalog = curSearchCatalog;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
		initData();
	}

	@Override
	public void onDestroyView() {
		lvSearchData.clear();
		super.onDestroyView();
	}

	// 初始化视图控件
	private void initView() {
		lvSearchAdapter = new ListViewSearchAdapter(getActivity(),
				lvSearchData, R.layout.search_listitem);
		listView.addFooterView(list_footer);// 添加底部视图 必须在setAdapter前
		listView.setAdapter(lvSearchAdapter);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 点击底部栏无效
				if (view == list_footer)
					return;

				Result res = null;
				// 判断是否是TextView
				if (view instanceof TextView) {
					res = (Result) view.getTag();
				} else {
					TextView title = (TextView) view
							.findViewById(R.id.search_listitem_title);
					res = (Result) title.getTag();
				}
				if (res == null)
					return;

				// 跳转
				UIHelper.showUrlRedirect(view.getContext(), res.getUrl());
			}
		});
		listView.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// 数据为空--不用继续下面代码了
				if (lvSearchData.size() == 0)
					return;

				// 判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if (view.getPositionForView(list_footer) == view
							.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}

				if (scrollEnd && curLvDataState == UIHelper.LISTVIEW_DATA_MORE) {
					listView.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					list_foot_more.setText(R.string.load_ing);
					list_foot_progress.setVisibility(View.VISIBLE);
					// 当前pageIndex
					int pageIndex = lvSumData / 20;
					loadLvSearchData(curSearchCatalog, pageIndex,
							mSearchHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
			}
		});
	}

	// 初始化控件数据
	private void initData() {
		mSearchHandler = new Handler() {
			public void handleMessage(Message msg) {

				if (msg.what >= 0) {
					SearchList list = (SearchList) msg.obj;
					Notice notice = list.getNotice();
					// 处理listview数据
					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSumData = msg.what;
						lvSearchData.clear();// 先清除原有数据
						lvSearchData.addAll(list.getResultlist());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvSumData += msg.what;
						if (lvSearchData.size() > 0) {
							for (Result res1 : list.getResultlist()) {
								boolean b = false;
								for (Result res2 : lvSearchData) {
									if (res1.getObjid() == res2.getObjid()) {
										b = true;
										break;
									}
								}
								if (!b)
									lvSearchData.add(res1);
							}
						} else {
							lvSearchData.addAll(list.getResultlist());
						}
						break;
					}

					if (msg.what < 20) {
						curLvDataState = UIHelper.LISTVIEW_DATA_FULL;
						lvSearchAdapter.notifyDataSetChanged();
						list_foot_more.setText(R.string.load_full);
					} else if (msg.what == 20) {
						curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
						lvSearchAdapter.notifyDataSetChanged();
						list_foot_more.setText(R.string.load_more);
					}
					// 发送通知广播
					if (notice != null) {
						UIHelper.sendBroadCast(getActivity(), notice);
					}
				} else if (msg.what == -1) {
					// 有异常--显示加载出错 & 弹出错误消息
					curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
					list_foot_more.setText(R.string.load_error);
					((AppException) msg.obj).makeToast(getActivity());
				}
				if (lvSearchData.size() == 0) {
					curLvDataState = UIHelper.LISTVIEW_DATA_EMPTY;
					list_foot_more.setText(R.string.load_empty);
				}
				list_foot_progress.setVisibility(View.GONE);
				mPullToRefreshAttacher.setRefreshComplete();
				if (msg.arg1 != UIHelper.LISTVIEW_ACTION_SCROLL) {
					listView.setSelection(0);// 返回头部
				}
			}
		};
	}

	/**
	 * 线程加载收藏数据
	 * 
	 * @param type
	 *            0:全部收藏 1:软件 2:话题 3:博客 4:新闻 5:代码
	 * @param pageIndex
	 *            当前页数
	 * @param handler
	 *            处理器
	 * @param action
	 *            动作标识
	 */
	private void loadLvSearchData(final String catalog, final int pageIndex,
			final Handler handler, final int action) {
		if (StringUtils.isEmpty(curSearchContent)) {
			// UIHelper.ToastMessage(Search.this, "请输入搜索内容");
			mPullToRefreshAttacher.setRefreshing(false);
			return;
		}
		mPullToRefreshAttacher.setRefreshing(true);
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					SearchList searchList = appContext.getSearchList(catalog,
							curSearchContent, pageIndex, 20);
					msg.what = searchList.getPageSize();
					msg.obj = searchList;
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
					msg.obj = e;
				}
				msg.arg1 = action;// 告知handler当前action
				if (curSearchCatalog.equals(catalog))
					handler.sendMessage(msg);
			}
		}.start();
	}

	@Override
	public void showList() {
		loadLvSearchData(curSearchCatalog, 0, mSearchHandler,
				UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
	}

	@Override
	public void onRefreshStarted(View view) {
		loadLvSearchData(curSearchCatalog, 0, mSearchHandler,
				UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
	}

	public String getCurSearchContent() {
		return curSearchContent;
	}

	public void setCurSearchContent(String curSearchContent) {
		this.curSearchContent = curSearchContent;
	}


}
